package com.rank.ccms.validator;


import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;


/**
 * Created with IntelliJ IDEA.
 * User: SABIR IQBAL
 * Date: 1/2/14
 * Time: 12:29 AM
 * To change this template use File | Settings | File Templates.
 */

public class PhoneNumberValidator implements Validator {

    public PhoneNumberValidator() {
    }

    public void validate(
            FacesContext context, UIComponent component, Object value)
            throws ValidatorException {
        String strValue = (String) value;
        checkForNumbersOnly(strValue);
        if (strValue.length() != 10) {
            throwException("Number of phone digits must be 10");
        }
    }

    private void checkForNumbersOnly(String strValue) {
        try {
            long phoneNumber = Long.parseLong(strValue);
        } catch (Exception exception) {
            throwException("All Phone Digits must be of numbers only.");
        }
    }

    private void throwException(String errMessage) {
        FacesMessage message = new FacesMessage();
        message.setDetail(errMessage);
        message.setSummary(errMessage);
        message.setSeverity(FacesMessage.SEVERITY_ERROR);
        throw new ValidatorException(message);
    }

}
